package com.example.ex_jd.utils;

import com.example.ex_jd.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 77317
 * @Title: HtmlParseUtil
 * @projectName ex_jd
 * @description: TODO
 * @date 2020/5/10 23:55
 * @Version V1.0
 */
@Component
public class HtmlParseUtil {
    public static void main(String[] args)  throws IOException {
        new HtmlParseUtil().praresJd("心理学").forEach(System.out::println);

    }
    public List<Content> praresJd(String keywords) throws IOException{
        //获取请求  https://search.jd.com/Search?keyword=java
        //前提需要联网，
        String url="https://search.jd.com/Search?keyword="+keywords;
        //解析网页  jsoup返回的 Document就是浏览器Doucment对象
        Document parse = Jsoup.parse(
                new URL(url), 30000);
        //所有js能用的都可以用
        //获取当前节点元素
        Element element = parse.getElementById("J_goodsList");
        //获取所欲的li元素
        Elements li = element.getElementsByTag("li");
        ArrayList<Content> objects = new ArrayList<>();
        //获取元素中的内容
        for(Element el:li){
            //获取第一个元素 下的src标签
            String img = el.getElementsByTag("img").eq(0).attr("src");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            objects.add(new Content(title,img,price));

        }
        return  objects;
    }

}
